<?php
require_once(dirname(dirname(dirname(__FILE__))) . '/app.php');
define('CACHE_PATH',dirname(dirname(dirname(__FILE__))).'/' );
define('PHPCMS_PATH',dirname(dirname(dirname(__FILE__))).'/' );
@set_time_limit(0);
new upgrade();
class upgrade{
	private $_filearr = array('api', 'phpcms', 'statics', '');
	//md5验证地址
	private $_upgrademd5 = 'http://pin.liofis.com/';
	//补丁地址
	private $_patchurl = 'http://pin.liofis.com/version.php';
	
	public function __construct() {
		$this->init();
	}
	
	public function init() {
		global $INI;
		$upgrade_path_base = $this->_patchurl;
		//获取当前版本
		$current_version = isset($INI['system']['version']) ? $INI['system']['version'] :'V2.0';
		$host = strtolower(strval($_SERVER['HTTP_HOST']));
		
		$pathlist_str = @file_get_contents($upgrade_path_base.'?version='.$current_version.'&host='.$host);
		$pathlist = $allpathlist = array();
		$key = -1;
		//获取压缩包列表
		$allpathlist = json_decode($pathlist_str,true);
			//开始升级
			//创建缓存文件夹
			if(!file_exists(CACHE_PATH.'caches_upgrade')) {
				@mkdir(CACHE_PATH.'caches_upgrade');
			}
			//根据版本下载zip升级包，解压覆盖
			$pathlist = $allpathlist;
			foreach($pathlist as $k=>$v) {
				
				//远程压缩包地址
				$upgradezip_url = $this->_upgrademd5.'server.php?vs='.$k;
				//保存到本地地址
				$upgradezip_path = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.$v['name'];
				
				//解压路径
				$upgradezip_source_path = CACHE_PATH.'caches_upgrade'.DIRECTORY_SEPARATOR.substr($v['name'],0,-4);
				
				//下载压缩包
				@file_put_contents($upgradezip_path, file_get_contents($upgradezip_url));
				//解压缩
				$archive = new PclZip($upgradezip_path);
				//var_dump($upgradezip_path,$upgradezip_source_path);die();
				if($archive->extract(PCLZIP_OPT_PATH, $upgradezip_source_path, PCLZIP_OPT_REPLACE_NEWER) == 0) {
					die("Error : ".$archive->errorInfo(true));
				}
							
				//拷贝gbk/upload文件夹到根目录
				$copy_from = $upgradezip_source_path.DIRECTORY_SEPARATOR.$patch_charset;
				
				$copy_to = PHPCMS_PATH;
				
				$this->copyfailnum = 0;
				$this->copydir($copy_from, $copy_to, $_GET['cover']);
				
				//检查文件操作权限，是否复制成功
				if($this->copyfailnum > 0) {
					//如果失败，恢复当前版本
					@file_put_contents(CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.'version.php', '<?php return '.var_export($current_version, true).';?>');
					die('no');
					
				}
				
				//执行sql
				//sql目录地址
				$sql_path = $copy_from.'/sql.txt';
				if(file_exists($sql_path))
				{
					$data = file_get_contents($sql_path);
					$sqls = explode(';', $data);
					foreach ($sqls as $sqlv) {
						if (empty($sqlv)) continue;
						if(mysql_get_server_info > '4.1') {
							$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET=".$dbcharset,$sqlv);
						}
						echo $sqlv;
						$r = DB::Query($sqlv);
					}
				}
				$INI = Config::MergeINI($INI, array('system' => array('version'=>$k)));
				$INI = ZSystem::GetUnsetINI($INI);
				save_config();
		}	
		Session::Set('notice', '一键更新成功');
		redirect( WEB_ROOT . '/manage/system/upgrade.php');	
	}
	
	
	//检查文件md5值
	public function checkfile() {
		if(!empty($_GET['do'])) {
			$this->md5_arr = array();
			$this->_pc_readdir(".");

			//读取phpcms接口
			$current_version = pc_base::load_config('version');
			$phpcms_md5 = @file_get_contents($this->_upgrademd5.$current_version['pc_release'].".php");
			$phpcms_md5_arr = json_decode($phpcms_md5, 1);
			//计算数组差集
			$diff = array_diff($phpcms_md5_arr, $this->md5_arr);

			//丢失文件列表
			$lostfile = array();
			foreach($phpcms_md5_arr as $k=>$v) {
				if(!in_array($k, array_keys($this->md5_arr))) {
					$lostfile[] = $k;
					unset($diff[$k]);
				}
			}
			
			//未知文件列表
			$unknowfile = array_diff(array_keys($this->md5_arr), array_keys($phpcms_md5_arr));
			
			
		} else {
		
		}
	}
	
	private function _pc_readdir($path='') {
		$dir_arr = explode('/', dirname($path));
		if(is_dir($path)) {
			$handler = opendir($path);
			while(($filename = readdir($handler)) !== false) {
				if(substr($filename, 0, 1) != ".") {
					$this->_pc_readdir($path.'/'.$filename);
				}
			}
			closedir($handler);
		} else {

			if (dirname($path) == '.' || (isset($dir_arr[1]) && in_array($dir_arr[1], $this->_filearr))) {
				$this->md5_arr[base64_encode($path)] = md5_file($path);
			}
		}
	}
	
	public function copydir($dirfrom, $dirto, $cover='') {
	    //如果遇到同名文件无法复制，则直接退出
	    if(is_file($dirto)){
	        die(L('have_no_pri').$dirto);
	    }
	    //如果目录不存在，则建立之
	    if(!file_exists($dirto)){
	        mkdir($dirto);
	    }
	    
	    $handle = opendir($dirfrom); //打开当前目录
    
	    //循环读取文件
	    while(false !== ($file = readdir($handle))) {
	    	if($file != '.' && $file != '..'){ //排除"."和"."
		        //生成源文件名
			    $filefrom = $dirfrom.DIRECTORY_SEPARATOR.$file;
		     	//生成目标文件名
		        $fileto = $dirto.DIRECTORY_SEPARATOR.$file;
		        if(is_dir($filefrom)){ //如果是子目录，则进行递归操作
		            $this->copydir($filefrom, $fileto, $cover);
		        } else { //如果是文件，则直接用copy函数复制
		        	if(!empty($cover)) {
						if(!copy($filefrom, $fileto)) {
							$this->copyfailnum++;
						    echo '复制'.$filefrom.'到'.$fileto.'失败'."<br />";
						}
		        	} else {
		        		if(fileext($fileto) == 'html' && file_exists($fileto)) {

		        		} else {
		        			if(!copy($filefrom, $fileto)) {
								$this->copyfailnum++;
							    echo '复制'.$filefrom.'到'.$fileto.'失败'."<br />";
							}
		        		}
		        	}
		        }
	    	}
	    }
	}
	
	function deletedir($dirname){
	    $result = false;
	    if(! is_dir($dirname)){
	        echo " $dirname is not a dir!";
	        exit(0);
	    }
	    $handle = opendir($dirname); //打开目录
	    while(($file = readdir($handle)) !== false) {
	        if($file != '.' && $file != '..'){ //排除"."和"."
	            $dir = $dirname.DIRECTORY_SEPARATOR.$file;
	            //$dir是目录时递归调用deletedir,是文件则直接删除
	            is_dir($dir) ? $this->deletedir($dir) : unlink($dir);
	        }
	    }
	    closedir($handle);
	    $result = rmdir($dirname) ? true : false;
	    return $result;
	}
	
}

function fileext($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}